package Communication;



import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import lejos.nxt.LCD;
import lejos.nxt.comm.BTConnection;
import lejos.nxt.comm.Bluetooth;


public class NECommunication extends Thread {

	private DataInputStream inputStream;
	private DataOutputStream outputStream;
	private NEMain robot;
	private boolean isRunning; 
	

	public NECommunication(NEMain robot) {
		this.robot = robot;

		this.connexion();

		isRunning = true;
	}
	
	private void connexion() {
		LCD.clear();
		LCD.drawString("Connexion...",0,0);
		LCD.refresh(); 

		BTConnection btc = Bluetooth.waitForConnection();

		inputStream = btc.openDataInputStream();
		outputStream = btc.openDataOutputStream();
		
		LCD.clear();
		LCD.drawString("Connexion OK",0,0);
		LCD.refresh();
		
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e1) {
		}
	}
	

	public void run(){
		while (isRunning) {
			char c = getCommande();

			if (c != '_'){		
				LCD.drawInt(c,7,0,1);		
				robot.interprete(c);
				
			}
			
		}
		
		try {
			inputStream.close();
			outputStream.close();
		} catch (Exception e) {
			robot.incident();
		}
	}

	public char getCommande() {
		char c = '0';
		while (c=='0')
		{
			try {
				c = inputStream.readChar();
			} catch (IOException e) {
				robot.incident();
			}			
		}

		return c;
	}

	public void kill() {
		// TODO Auto-generated method stub
		isRunning = false;
	}
	
	public void send(char commande){
		try{
			outputStream.writeChar(commande);
			outputStream.flush();
		} catch (IOException e) {
			robot.incident();
		}			
	}
	
}
